package com.itheima.gateway.filters;

import com.itheima.gateway.config.AuthProperties;

import com.itheima.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@RequiredArgsConstructor
@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    private final AuthProperties authProperties;

    private final AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 过滤所以请求
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        log.info("进入全局过滤器");
        // 获取请求
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否需要拦截
        if (isExcludePath(request.getURI().getPath())) {
            // 放行
            return chain.filter(exchange);
        }
        // 获取Jwt令牌
        String token = request.getHeaders().getFirst("authorization");
        log.info("token:{}",token);
        if (token == null || token.isEmpty()){
            // 没有获取到token,拦截请求
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 中止请求
            return response.setComplete();
        }
        // 解析并校验
        Claims claims = AppJwtUtil.getClaimsBody(token);
        log.info("claims:{}",claims);
        int statusCode = AppJwtUtil.verifyToken(claims);
        log.info("statusCode:{}",statusCode);
        if (statusCode == 0) {
            // TODO 刷新token
            System.out.println("刷新token");
        } else if (statusCode == 1) {
            // 拦截请求
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 中止请求
            return response.setComplete();
        } else if (statusCode != -1){
            // 拦截请求,设置响应状态码为401
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 中止请求
            return response.setComplete();
        }
        // 将用户信息封装到请求头中
        Long userId = claims.get("id", Long.class);
        ServerWebExchange swe = exchange.mutate()
                .request(builder -> builder.header("uid", userId.toString()))
                .build();
        // 放行
        return chain.filter(swe);
    }

    @Override
    public int getOrder() {
        return 0;
    }

    /**
     * 判断路径是否包含在拦截路径中
     * @param path
     * @return
     */
    public Boolean isExcludePath(String path) {
        for (String pathPattern : authProperties.getExcludePaths()) {
            if (antPathMatcher.match(pathPattern, path)) {
                return true;
            }
        }
        return false;
    }
}
